<?PHP

class OP_RecentCommentsWidget extends OP_WidgetTemplate{
	function render(){
		global $wpdb, $comment;
		
		$title = empty( $this->values['title'] ) ? __( 'Recent Comments' ) : apply_filters('widget_title', $this->values['title']);

		if ( !$quantity = (int) $this->values['quantity'] )
			$quantity = 10;
		else if ( $quantity < 1 )
			$quantity = 1;
		else if ( $quantity > 15 )
			$quantity = 15;

		if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) {
			$comments = $wpdb->get_results("SELECT comment_author, comment_author_url, comment_ID, comment_post_ID FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT $quantity");
			wp_cache_add( 'recent_comments', $comments, 'widget' );
		}
		
		echo $this->values['before_title'] . $title . $this->values['after_title'],
			'<ul class="multirecentcomments">';
			if ( $comments ){
				foreach ((array) $comments as $comment){
					echo  '<li class="recentcomments">' . sprintf(__('%1$s on %2$s'), get_comment_author_link(), '<a href="'. get_permalink($comment->comment_post_ID) . '#comment-' . $comment->comment_ID . '">' . get_the_title($comment->comment_post_ID) . '</a>') . '</li>';
				}
			}
			echo '</ul>';
	}
	
	
	function do_post($post){				
		$title = strip_tags(stripslashes($post["title"]));
		$quantity = (int) $post["quantity"];

		op_flush_widget_op_recent_comments();
		return compact( 'title','quantity');
	}

	function options(){		
		$title = attribute_escape($this->values['title']);
		
		echo '<p><label for="op_recent_comments-title-'.$this->values['number'].'">'._e('Title:').' <input class="widefat" id="op_recent_comments-title-'.$this->values['number'].'" name="widget_op_recent_comments['.$this->values['number'].'][title]" type="text" value="'.$title.'" /></label></p>',
			'<p>',
				'<label for="op_recent_comments-quantity-'.$this->values['number'].'">'._e('Number of comments to show:').' <input style="width: 25px; text-align: center;" id="op_recent_comments-quantity-'.$this->values['number'].'" name="widget_op_recent_comments['.$this->values['number'].'][quantity]" type="text" value="'.$this->values['quantity'].'" /></label>',
				'<br />',
					'<small>(at most 15)</small>',
			'</p>';
	}
}

$widget = new OP_Widget('recent_comments');
$widget->setMeta('OP Recent Comments',"The most recent comments");
$widget->setDefaults(array('title'=>'','quantity'=>5));

$opw_recent_comments = new OP_RecentCommentsWidget($widget);
add_action('widgets_init', array($opw_recent_comments, 'init'));

/**
 * Flush cache when 'comment_post' or'wp_set_comment_status' occurs
 */
 function op_flush_widget_op_recent_comments() {
	wp_cache_delete( 'widget_op_recent_comments', 'widget' );
}
add_action( 'comment_post', 'op_flush_widget_op_recent_comments' );
add_action( 'wp_set_comment_status', 'op_flush_widget_op_recent_comments' );

?>